<template>
  <div class="add-health-manage p-10">
    <el-form :model="personInfo" :rules="rules">
      <el-row>
        <el-col :span="7">
          <el-form-item label="姓名" required label-width="7em">
            <el-input
              v-model="personInfo.name"
              placeholder="请输入姓名"
            ></el-input>
           
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="证件号码" required label-width="7em">
            <el-input
              v-model="personInfo.cardNumber"
              placeholder="请输入证件号码"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="出生日期" required label-width="7em">
            <el-date-picker
            :disabled-date="disableFutureDates"
              v-model="personInfo.birthday"
              value-format="YYYY-MM-DD"
              type="date"
              placeholder="请选择出生日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-table
        class="mb-20"
        :data="questionTableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column
          v-for="(col, index) in dataCols"
          :align="index === 0 ? 'left' : 'center'"
          :prop="col.prop"
          :label="col.label"
          :key="col.prop + index"
        >
          <template #header="{ column }">
            <div v-html="column.label"></div>
          </template>
          <template #default="{ row, $index, column }">
            <template v-if="column.property === 'question'">
              <div>( {{ $index + 1 }} ) {{ row.question }}</div>
            </template>
            <template v-else>
              <div :key="index + Math.random()">
                <el-radio
                  @click.native="radioChange"
                  v-model="row.score"
                  :value="column.no"
                  ><span class="px-10">{{ column.no }}</span></el-radio
                >
              </div>
              <div v-if="row.extraTip">
                {{ row.extraTip[column.no - 1] }}
              </div>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <el-table
        :data="bodyTypeTableDataRender"
        :header-cell-class-name="headerCellClassFunc"
        border
        style="width: 100%"
      >
        <el-table-column
          v-for="(col, index) in bodyTypeCols"
          header-align="center"
          align="left"
          :prop="col.prop"
          :label="col.label"
          :key="index + col.prop"
        >
          <template #default="{ column, $index }">
            <div v-if="index === 0">
              {{ leftLabels[$index] }}
            </div>
            <div v-else-if="$index === 0">
              得分:
              {{
                bodyTypeDataObj[`${column.property}${bodyTypebValKeys[$index]}`]
              }}
              <div v-if="$index === 0">
                <el-radio-group
                  disabled
                  v-model="bodyTypeDataObj[`${column.property}Choice`]"
                >
                  <el-radio value="1">是</el-radio>
                  <el-radio value="2">{{
                    index !== 9 ? "倾向是" : "基本是"
                  }}</el-radio>
                  <el-radio value="3">否</el-radio>
                </el-radio-group>
              </div>
            </div>
            <div v-else>
              <el-checkbox-group
                v-model="bodyTypeDataObj[`${column.property}Guidance`]"
              >
                <el-checkbox
                  v-for="(item, gIndex) in healthGuidance"
                  :key="item"
                  :label="gIndex + 1"
                  :value="gIndex + 1"
                >
                  {{ item }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="d-flex jc-center py-10 mt-30">
        <el-button plain>取消</el-button>
        <el-button type="primary" @click="saveData">保存</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import {
  getDataCols,
  getQuestionTableData,
  getBodyTypeTableData,
  getBodyTypeCols,
  healthGuidance,
} from "@/pages/examples/addHealth/constants.js";
const disableFutureDates = (time) =>  time > new Date();
export default {
  data() {
    const validatorIdCard = (rule, value, callback) => {
      setTimeout(() => {
        //@ts-ignore
        const value2 = this.personInfo.cardNumber;
        if (value2 == "") {
          callback(new Error("请输入证件号码"));
          //@ts-ignore
        } else if (
          //@ts-ignore
          !/^\d{15}|^\d{17}[a-z]$/i.test(value2)
        ) {
          callback(new Error("请输入正确的证件号码"));
        } else {
          callback();
        }
      }, 200);
    };
    return {
      dataCols: getDataCols(),
      questionTableData: getQuestionTableData(),
      bodyTypeDataObj: getBodyTypeTableData().bodyTypeDataObj,
      bodyTypeTableDataRender: getBodyTypeTableData().bodyTypeTableDataRender,
      bodyTypeCols: getBodyTypeCols(),
      healthGuidance,
      redHeaderPropArr: [],
      valueArr: [],
      leftLabels: ["体质辨识", "中医药保健指导"],
      bodyTypebValKeys: ["Score", "Guidance"],
      personInfo: {
        userName: "",
        cardNumber: "",
        birthday: "",
      },
      rules: {
        userName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        cardNumber: [
          { required: true, validator: validatorIdCard, trigger: "blur" },
        ],
        birthday: [
          { required: true, message: "请选择出生日期", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    // bodyTypeDataObj 第一个key 生成的三个数据 仅用于展示文字，与需要提交的数据字段无关联因此不需要考虑
    bodyTypeDataKeys() {
      return Object.keys(this.bodyTypeDataObj).slice(3);
    },
  },
  methods: {
    disableFutureDates,
    headerCellClassFunc({ column }) {
      const { property } = column;
      const { redHeaderPropArr, valueArr } = this;
      return redHeaderPropArr.includes(property) && valueArr.some(Boolean)
        ? "red-header-cell"
        : "";
    },
    saveData() {
      const {
        bodyTypeDataObj,
        questionTableData,
        personInfo,
        bodyTypeDataKeys,
      } = this;
      const submitObj = { ...personInfo };
      questionTableData.forEach((item) => {
        submitObj[item.questionId] = item.score;
      });

      bodyTypeDataKeys.forEach((key) => {
        submitObj[key] = bodyTypeDataObj[key];
        // 提交数据时，需要将checkbox数组转为字符串
        if (key.includes("Guidance")) {
          submitObj[key] = submitObj[key].join(",");
        }
      });
    
    },
    radioChange() {
      const totalScoreMap = {};
      const { bodyTypeCols, bodyTypeDataObj, questionTableData } = this;
      const dataCols = bodyTypeCols.slice(1);
      dataCols.forEach((item) => {
        const { relateQuestions, prop, label } = item;
        const totalScore = questionTableData
          .filter((_v, index) => relateQuestions.includes(index + 1))
          .reduce((pre, cur) => {
            let { score } = cur;
            const isReverseScore = label === "平和质";
            if (isReverseScore) {
              score = score === 0 ? 0 : 6 - score;
            }
            return pre + score;
          }, 0);
        totalScoreMap[prop] = totalScore;
        bodyTypeDataObj[`${prop}Score`] = totalScore;
      });
      const propArr = Object.keys(totalScoreMap);
      const valueArr = Object.values(totalScoreMap);
      let redHeaderPropArr = propArr.filter((_v, index) => valueArr[index] >= 11);
      bodyTypeDataObj.peacefulQualityChoice !== "1" &&
        (redHeaderPropArr = redHeaderPropArr.filter((v) => v !== "peacefulQuality"));
      this.valueArr = valueArr;
      this.redHeaderPropArr = redHeaderPropArr;
      // ②除平和质外
      //  a.各体质类型得分相加之和≥11 分时，体质辨识选中“是”
      //  b.各体质类型得分相加之和为 9～10 分,体质辨识选中“倾向是”
      //  c.各体质类型得分相加之和≤8 分,体质辨识选中“否”
      // ③平和质对应选项其中，（2）（4）（5）（13）需反向计分，即选 1→5 分，选 2→4 分，
      // 选 3→3 分，选 4→2 分，选 5→1 分
      //  a.各问题得分相加之和≥17 分，同时其他 8 种体质得分均≤ 8 分，体质辨识选中“是”
      //  b.各问题得分相加之和≥17 分，同时其他 8 种体质得分≤10 分，体质辨识选中“基本是”
      //  d.不满足上述条件时，体质辨识选中“否”
      dataCols.forEach((item, curIndex) => {
        const { prop } = item;
        const otherScores = dataCols
          .filter((_v, index) => index !== curIndex)
          .map((v) => totalScoreMap[v.prop]);
        let choiceVal = "3";
        const curTotalScore = totalScoreMap[item.prop];
        const basicTotalScoreGt17 = curTotalScore >= 17;
        if (item.label === "平和质") {
          const isPhz = basicTotalScoreGt17 && otherScores.every((v) => v <= 8);
          const basiclyIsPhz =
            basicTotalScoreGt17 && otherScores.every((v) => v <= 10);
          choiceVal = isPhz ? "1" : basiclyIsPhz ? "2" : "3";
        } else {
          const conditionIs = curTotalScore >= 11;
          const conditionIsBasicly = curTotalScore >= 9;
          choiceVal = conditionIs ? "1" : conditionIsBasicly ? "2" : "3";
        }
        bodyTypeDataObj[`${prop}Choice`] = choiceVal;
        const allGuidance = healthGuidance.map((_v, index) => index + 1);
        if (choiceVal === "1") {
          bodyTypeDataObj[`${prop}Guidance`] = allGuidance;
        } else {
          bodyTypeDataObj[`${prop}Guidance`] = [];
        }
      });
    },
  },
};
</script>

<style scoped>
:deep(.red-header-cell) {
  color: red;
}
.p-10 {
  padding: 10px;
}
.mt-30 {
  margin-bottom: 30px;
}
.d-flex {
  display: flex;
}
.jc-between {
  justify-content: space-between;
}
.jc-center {
  justify-content: center;
}
.ai-center {
  align-items: center;
}
.px-10 {
  padding-left: 10px;
  padding-right: 10px;
}
.py-10 {
  padding: 10px 0;
}
.mb-20 {
  margin-bottom: 20px;
}
.text-center {
  text-align: center;
}
.text-left {
  text-align: left;
}
</style>
